# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: jaewon

from absl import app
from tornado.ioloop import IOLoop

from coin.base.datetime_util import to_datetime
import coin.flow.subscriber as flow_subscriber
from coin.flow.simple_queue import SimpleQueue
from coin.strategy.mm.base.multi_feed_subsystem import MultiFeedSubsystem
from coin.feed.fastfeed.proto_feed_adapter import ProtoFeedAdapter

from experimental.prophet.graph import graph
from experimental.prophet.ops.fastfeed import fastfeed_coin
from experimental.prophet.ops.debug import printer

from experimental.prophet.craps.universe import universe_btc

from experimental.prophet.graph_runner.fastfeed import FastfeedGraphAdapter


def model(machine):
  for symbol_info in universe_btc()[2:10]:
    with graph.namespace(symbol_info.nickname):
      feed = fastfeed_coin(symbol_info.product, symbol_info.sub_req, machine)
      book = graph.create_node('fastfeed.BookBestLevel', [feed.book])
      # trade = graph.create_node('fastfeed.Trade', [feed.trade])

      printer('[%%t] %-30s A0 %%s@%%s - B0 %%s@%%s' % symbol_info.nickname,
              book.outputs[0],
              book.outputs[2],
              book.outputs[1],
              book.outputs[4],
              book.outputs[3])


def main(argv):
  ioloop = IOLoop.current()
  queue = SimpleQueue('queue')
  flow_sub = flow_subscriber.from_queue(queue)

  g = graph.Graph()
  with graph.as_default_graph(g):
    model('')

  adapter = FastfeedGraphAdapter(g, '')
  feed_sub_req = adapter.get_feed_sub_requests()

  feed_subsystem = MultiFeedSubsystem()
  feed_subsystem.subscribe_fastfeed(feed_sub_req, adapter.on_book_reset)

  feed_subsystem.start(ioloop, queue, flow_sub)

  try:
    ioloop.start()
    return 0
  except KeyboardInterrupt:
    return 1


if __name__ == '__main__':
  app.run(main)
